import axios from 'axios';
import {nanoid} from 'nanoid';
import Vue from 'vue'

import Vuex from 'vuex'

// 通过Vue加载这个插件
Vue.use(Vuex)


//模块化开发 组件之间的数据互相隔离开来
const countModule = {
    namespaced:true,
    actions:{
        jia(store,value){
            // console.log("add的dispatch被触发了",store,value);
            store.commit("JIA",value);
        },
        jian(store,value){
            store.commit("JIAN",value);
        },
        oddAdd(store,value){
            store.commit("ODDADD",value);
        },
        waitAdd(store,value){
            store.commit("WAITADD",value);
        },
    },
    mutations:{
        JIA(state,value){
            // console.log("add的commit被触发了",a,b);
            state.count += value
        },
        JIAN(state,value){
            state.count -= value
        },
        ODDADD(state,value){
            if(state.count % 2 != 0){
                state.count += value
            }
        },
        WAITADD(state,value){
            setTimeout(()=>{
                state.count += value
            },500)
        },
    },
    state:{
        count:0,
        studentName:'学生名称',
        schoolName:'二圣小学',
        smallName:'xfj',
    },
    getters:{
        ncount(state){
            return state.count * 10
        }
    }
}

const personModule = {
    namespaced:true,
    actions:{
        addPersonXW(store,value){
            if(value[0] === '王'){
                store.commit("ADDPERSON",value);
            }else{
                alert("只能添加姓王的人")
            }
        },
        addRandomPerson(store,value){
            axios.get('https://api.xygeng.cn/one').then(
                res=>{
                    //console.log(res.data.data.content);
                    let context = res.data.data.content;
                    store.commit("ADDPERSON",context);
                }
            )
        }
    },
    mutations:{
        ADDPERSON(state,value){
            state.personList.unshift({id:nanoid(),name:value})
        },
    },
    state:{
        personList:[{id:'001',name:'张三'}]
    },
    getters:{
        firstName(state){
            return state.personList[0].name;
        }
    }
}

export default new Vuex.Store({
    modules:{
        countModule,
        personModule
    }
    
})